<template>
  <div id="emergencyTaskArea" v-show="taskShow">
    
    <div id="tabs" >
      <div
        :class="this.tabSelected === 10 && !this.publish && 'focus'"
        @click="() => (this.tabSelected = 10) && (this.publish = false)"
      >
        数据处理任务
      </div>
      <div
        :class="this.tabSelected === 11 && !this.publish && 'focus'"
        @click="() => (this.tabSelected = 11) && (this.publish = false)"
      >
        监测产品生产任务
      </div>
      <div
        :class="this.tabSelected === 12 && !this.publish && 'focus'"
        @click="() => (this.tabSelected = 18) && (this.publish = false)"
      >
        制图任务
      </div>
      <div :class="this.publish && 'focus'"
        @click=" isPublishShow">
        发布监控
      </div>
      <img 
            src="@/assets/icons/shrink.png"
            alt="X"
            class="iconBtn2"
            @click="hideDrawer"
          />
    </div>
      
    <div v-if="this.publish === true">
      <Table
        :columns="publishColumn"
        border
        :data="publishData.slice(
              this.pageSelected * this.pageSize,
              (this.pageSelected + 1) * this.pageSize )"
      >
        <template slot-scope="{ row }" slot="status">
          <Button v-if="isFalse(row)" type="error">
            {{ row.status }}  </Button>
          <Button v-else class="primary"> {{ row.status }} </Button>
        </template>
        <template slot-scope="{ row  }" slot="action">
          <Button type="error" size="small" @click="deletePublish(row)">删除</Button>
        </template>
      </Table>
      <Page
        :total="publishData.length"
        :page-size="pageSize"
        show-total
        @on-change="changePage"
      ></Page>
    </div>

    <div v-else>
      <Table
        :columns="columnNames"
        border
        :data="
          taskData
            .filter((d) => d.taskSource === this.tabSelected)
            .slice(
              this.pageSelected * this.pageSize,
              (this.pageSelected + 1) * this.pageSize
            )
        "
      >
        <template slot-scope="{ row, index }" slot="status">
          <Button v-if="row.status == 1" class="stastusBtn executing">
            执行中
          </Button>
          <button v-if="row.status == 2" class="stastusBtn pause">暂停</button>
          <button v-if="row.status == 3" style="color: #f9b115">删除</button>
          <button v-if="row.status == 4" class="stastusBtn success">成功</button>
          <button v-if="row.status == 5" class="stastusBtn fail">失败</button>
          <button v-if="row.status == 6" style="color: #f9b115">超时</button>
          <button v-if="row.status == 7" class="stastusBtn stop">停止</button>
          <button v-if="row.status == 8" class="stastusBtn pending">
            待执行
          </button>
          <button v-if="row.status == -1" class="stastusBtn pending">
            未提交
          </button>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <Button
            type="primary"
            size="small"
            style="margin-right: 5px"
            @click="() => inspectTask(row)"
            >查看</Button
          >
          <Button
            type="primary"
            size="small"
            style="margin-right: 5px"
            @click="() => taskDetail(row)"
            >详情</Button
          >
          <!-- <Button
            type="primary"
            size="small"
            style="margin-right: 5px"
            @click="() => taskInteraction(row)"
            >交互</Button
          > -->
          <!-- <Button
            type="primary"
            size="small"
            style="margin-right: 5px"
            @click="() => downloadTask(row)"
            >下载</Button
          > -->
          <Button
            type="primary"
            size="small"
            style="margin-right: 5px"
            @click="() => terminateShow(row)"
            >终止</Button
          >
          <Button type="error" size="small" @click="() => deleteShow(row)"
            >删除</Button>
        </template>
      </Table>
      <Page
        :total="taskData.filter((d) => d.taskSource === this.tabSelected).length"
        :page-size="pageSize"
        show-total
        @on-change="changePage"
      ></Page>
    </div>

    <Modal v-model="stopShow" draggable scrollable title="终止任务">
      <p>确认要终止任务吗？</p>
      <template #footer class="footerBtns">
        <CButton @click="stopShow = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="terminateTask" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>

    <Modal
      v-model="delShow"
      draggable
      scrollable
      title="删除任务"
      :styles="modalStyle"
    >
      <p slot="header" class="modalHeader">
        <img src="@/assets/icons/shanchu.svg" alt />
        <span style="margin-left: 5px">删除任务</span>
      </p>
      <div class="modalBody">
        <p>删除任务时与任务相关的信息都会丢失</p>
        <p>请确认是否删除?</p>
      </div>
      <template #footer class="footerBtns">
        <CButton @click="delShow = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="deleteTask" color="info" class="system-btn-style"
          >确定</CButton
        >
      </template>
    </Modal>
    <Modal
      v-model="showDownload"
      draggable
      scrollable
      title="下载列表"
      :styles="modalStyle"
      class="downLoadModal"
    >
      <!-- 复选 : show-checkbox -->
      <Tree
        @on-select-change="selectTree"
        :data="treeData"
        ref="tree"
        class="demo-tree-render"
        style="overflow: auto"
      ></Tree>

      <template #footer class="footerBtns">
        <CButton @click="showDownload = false" color="info" class="cancel-btn"
          >取消</CButton
        >
        <CButton @click="downloadProduct" color="info" class="system-btn-style"
          >下载</CButton
        >
      </template>
    </Modal>
  </div>
</template>

<script>
import Axios from "axios";

export default {
  name: "taskArea",
  components: {},
  props: {
     modelShow: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      taskShow:false,
      timer: "",
      taskId: -1,
      tabSelected: 10,
      taskData: [],
      publishData: [],
      dataCount: 0,
      pageSize: 3,
      pageSelected: 0,
      columnNames: [
        {
          title: "序号",
          key: "id",
          className: "centerCol",
          width: 100,
        },
        {
          title: "任务名称",
          key: "groupTaskName",
          className: "taskNameCol",
        },
        {
          title: "创建时间",
          key: "createTime",
          className: "centerCol",
          width: 200,
        },
        {
          title: "结束时间",
          key: "endTime",
          className: "centerCol",
          width: 200,
        },
        {
          title: "成功",
          key: "successNumber",
          className: "centerCol",
          width: 80,
        },
        {
          title: "失败",
          key: "failNumber",
          className: "centerCol",
          width: 80,
        },
        {
          title: "状态",
          slot: "status",
          align: "center",
          width: 132,
        },
        {
          title: "操作",
          slot: "action",
          width: 320,
          align: "center",
        },
      ],
      publishColumn: [
        {
          title: "序号",
          key: "index",
          className: "centerCol",
          width: 100,
        },
        {
          title: "数据名称",
          key: "path",
          className: "taskNameCol",
          align: "center",
        },
        {
          title: "目标事件",
          key: "eventName",
          className: "taskNameCol",
          align: "center",
        },
        {
          title: "产品类型",
          key: "type",
          className: "taskNameCol",
          align: "center",
          width: 150,
        },
        {
          title: "开始时间",
          key: "createTime",
          className: "centerCol",
          width: 200,
        },
        {
          title: "状态",
          slot: "status",
          align: "center",
          width: 132,
        },
        {
          title: "操作",
          slot: "action",
          width: 150,
          align: "center",
        },
      ],
      modalStyle: { top: "200px" },
      stopShow: false,
      delShow: false,
      clickId: void 0,
      showDownload: false,
      treeData: [],
      productpath: "",
      someStatus: [
        "",
        "执行中",
        "暂停",
        "删除",
        "成功",
        "失败",
        "超时",
        "停止",
        "待执行",
        "部分失败",
      ],
      someClasses: [
        "",
        "blue",
        "grey",
        "red",
        "green",
        "red",
        "red",
        "grey",
        "grey",
        "yellow",
      ],
      publish: false
    };
  },
  methods: {
    //发布显示
    isPublishShow(){
      this.publish = true
    },
    getPublishData(){
      let path = this.$api.emergencyMonitorApi.getPublishData 
      let params = {
        taskId: this.taskId
      } 
      this.http.get(path,params).then(res => {
        console.log(res.data)
        if(res.data.success){
          let result = res.data.data
          this.publishData = [];
          result.forEach((item,index) => {
              let path = item.path.split("/")
              let obj = {
                index: index + 1,
                createTime: item.createTime,
                dataId:item.dataId,
                eventId: item.eventId,
                eventName:item.eventName,
                id: item.id,
                path:path[path.length - 1],
                status:item.status,
                taskId:item.taskId,
                type:item.type,
                updateTime:item.updateTime
              }
              this.publishData.push(obj)
          });
        }
      })
      console.log(this.publishData)
    },
    isFalse(row){
      console.log(row)
      return row.status.includes("失败") || row.status.includes("错误")
    },
    deletePublish(val){
      let path =  this.$api.emergencyMonitorApi.deletePublish + val.id
      this.http.delete(path).then(res => {
        if(res.data.success){
          this.$Message.info("删除成功")
          console.log(this.pageSelected)
          console.log(this.publishData.length)
          console.log((this.pageSelected  * this.pageSize + 1))
          let pageIndex = this.pageSelected * this.pageSize + 1
          if( this.publishData.length === pageIndex && pageIndex > 1 ){
            this.pageSelected = this.pageSelected - 1
            console.log(this.pageSelected)
          }
          this.getPublishData()
        }
      })
    },
    // 获取任务列表
    async getData() {
      if (this.taskId === -1) return;

      const path = this.$api.emergencyMonitorApi.queryTaskWithId;
      const { data } = await Axios.get(path + this.taskId);

      if (!data || data.code !== 200) {
        this.$Message.warning("通过任务id获取任务列表失败");
        return;
      }

      const taskData = data.data && data.data.taskInfoList;
      this.taskData = taskData || [];
    },

    changePage(index) {
      this.pageSelected = index - 1;
    },

    // 查看
    inspectTask(row) {
      String.prototype.replaceAll = function (s1, s2) {
        return this.replace(new RegExp(s1, "gm"), s2);
      };

      let userLink =
        `/taskManage/allTask/${row.id}/${row.groupTaskName.replaceAll(
          "/",
          "*"
        )}` + "?";
      // this.$router.push({
      //   path: userLink,
      //   query: {
      //     // pageNum: this.pageNum,
      //     from: "taskLook",
      //     taskType: row.taskSource,
      //   },
      // });
       const href = this.$router.resolve({
        path:userLink,
        query: {
         from: "taskLook",
          taskType: row.taskSource,
        }
      });
      window.open(href.href, "_blank");
    },
    // 详情
    taskDetail(row) {
      // this.$router.push({
      //   path: "/processing",
      //   query: {
      //     from: "taskLook",
      //     id: row.id,
      //     status: row.status,
      //   },
      // });
        const href1  = this.$router.resolve({
        path:"/processing",
        query: {
         from: "taskLook",
          id: row.id,
          status: row.status,
        },
      });
      window.open(href1.href, "_blank");
      
    },
    // //交互
    // taskInteraction(row){

    // },
    //下载
    async downloadTask(row) {
      let path = this.$api.taskManageApi.taskDetailResult + row.id;
      // TODO: 需要筛选是否存在product，对接后端

      const { data } = await Axios.get(path, {
        params: {
          productType: -1,
        },
      });
      if (!data || data.code != 0) {
        this.$Message.warning((data && data.message) || "获取影像产品数据失败");
      } else if (!data.data || data.data.length === 0) {
        this.$Message.warning("暂无影像产品数据");
      } else {
        this.showDownload = true;
        this.treeData = this.getNewTreeData(data.data);
      }
    },

    downloadProduct() {
      // this.productpath =
      //   "/pie/data/247/sthx_user_data/pieadmin/lilintest/123/GF3_KAS_QPSI_010970_E81.2_N40.5_20180910_L1A_VH_L10003442728.tif";
      if (!this.productpath) {
        this.$Message.warning("请选择下载的产品文件");
        return;
      }

      let newarr = [];
      newarr.push(this.productpath);
      let path = this.$api.taskManageApi.downloadReport + newarr;
      window.open(path);
    },

    //提取文件夹里面所有的文件
    getNewTreeData(data) {
      let result = [];
      for (let i = 0; i < data.length; i++) {
        let tempItem = data[i];
        let item = {};
        item.expand = tempItem.expand;
        item.path = tempItem.path;
        item.title = tempItem.title;
        item.type = tempItem.type;
        item.children = [];
        result.push(item);

        if (tempItem.type == "folder" && tempItem.children) {
          let list = [];
          this.recursiveTreeFile(tempItem.children, list);
          item.children = list;
        }
      }
      return result;
    },

    recursiveTreeFile(data, list) {
      for (let i = 0; i < data.length; i++) {
        let tempItem = data[i];
        if (tempItem.type == "file") {
          list.push(tempItem);
        }
        if (tempItem.type == "folder" && tempItem.children) {
          this.recursiveTreeFile(tempItem.children, list);
        }
      }
      return list;
    },

    selectTree() {
      let item = this.$refs.tree.getSelectedNodes()[0];
      if (!item) return;
      this.productpath = this.$refs.tree.getSelectedNodes()[0].path;
      if (item.type === "folder") {
        item.expand = !item.expand;
        item.selected = !item.selected;
        return;
      }
    },

    terminateShow(row) {
      this.stopShow = true;
      this.clickId = row.id;
    },

    // 终止
    async terminateTask() {
      this.stopShow = false;
      let path = this.$api.taskManageApi.updateStatus + "/" + this.clickId;

      const formdata = new FormData();
      formdata.append("statusName", "STOP");

      const { data } = await Axios.put(path, formdata);
      if (!data || !data.success) {
        this.$Message.warning((data && data.message) || "终止任务失败");
      } else {
        // Success
        // Update view
        await this.getData();
      }
    },

    deleteShow(row) {
      this.delShow = true;
      this.clickId = row.id;
    },
    // 删除
    async deleteTask() {
      this.delShow = false;
      let path = this.$api.taskManageApi.delete + this.clickId;

      const { data } = await Axios.delete(path);
      if (!data || !data.success) {
        this.$Message.warning((data && data.message) || "删除任务失败");
      } else {
        // Success

        // Update view
        await this.getData();
      }
    },
     hideDrawer() {
      this.$emit("taskControlHide");
    },
  },
  watch: {
    taskId: {
      handler(val) {
        this.getData();
      },
      immediate: true,
    },
    modelShow: {
      handler(val) {
        this.taskShow = val;
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.taskId = this.$route.query.id;

    this.getPublishData()
    this.timerPublish = setInterval(() => {
      this.getPublishData();
    }, 10000);
    this.getData();
    this.timer = setInterval(() => {
      this.getData();
    }, 10000);
  },
  destroyed() {
    clearInterval(this.timer);
    clearInterval(this.timerPublish);
    this.timer = null;
    this.timerPublish = null;
  },
};
</script>

<style lang="scss">
#emergencyTaskArea {
  width: 100%;
  height: 100%;
  margin: -16px;

  font-family: Microsoft YaHei, monospace;
}

#emergencyTaskArea #tabs {
  display: flex;
}
#emergencyTaskArea #task {
  display: flex;
}
#emergencyTaskArea #tabs img {
 transform:rotate(270deg);

}

#emergencyTaskArea #tabs div {
  box-sizing: border-box;
  width: 10em;
  padding: 10px;
  text-align: center;

  cursor: pointer;
}

#emergencyTaskArea #tabs div.focus,
#emergencyTaskArea #tabs div:hover {
  color: #5290e8;
  border-bottom: 1px solid #5290e8;
}

#emergencyTaskArea .ivu-table-wrapper {
  height: 100%;
  width: 100%;
}

#emergencyTaskArea .ivu-table-overflowX {
  overflow-x: hidden;
}

#emergencyTaskArea .ivu-table-body {
  display: block !important;
  height: 180px;
  overflow-x: hidden;
  overflow-y: scroll;
}

#emergencyTaskArea .ivu-table-header thead tr th {
  text-align: center !important;
}

#emergencyTaskArea .ivu-table-tip {
  display: none;
}

#emergencyTaskArea button {
  cursor: pointer;
}

#emergencyTaskArea .ivu-page {
  height: 20%;

  text-align: center;
  margin-top: 5px;
  margin-right: 180px;
}

#emergencyTaskArea .ivu-page-total {
  margin-right: 60px;
}

.statusBtn {
  width: 5em;
  border: none;
  border-radius: 4px;
  cursor: default !important;
}

.statusBtn span,
.statusBtn:hover span {
  color: white;
}
.statusBtn.red,
.statusBtn.red:hover {
  background-color: red;
}
.statusBtn.blue,
.statusBtn.blue:hover {
  background-color: #5290e8;
}
.statusBtn.yellow,
.statusBtn.yellow:hover {
  background-color: yellow;
}
.statusBtn.green,
.statusBtn.green:hover {
  background-color: rgb(103, 185, 165);
}
.statusBtn.grey,
.statusBtn.grey:hover {
  background-color: rgb(200, 200, 200);
}

.centerCol {
  text-align: center !important;
  width: auto;
}
 .iconBtn2 {
  position: absolute;
  bottom: 260px;
  right: 0;
  height: 36px;
  // border-radius: 50%;
  z-index: 3;
  transform:rotate(90deg);
}
 .iconBtn2:hover {
  opacity: 1 !important;
} 

</style>